package com.juyu.miliao.api.dao.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.cache.RedisKeyPrefix;
import com.juyu.miliao.api.dao.mysql.OfficialQuestionToAnswerDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.domain.OfficialQuestionToAnswerInfo;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.constant.OfficialQuestionToAnsweRedisKey;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 * @create 2018-18-2:05 PM
 */
@Component
public class OfficialQuestionToAnsweRedis {


//    public static final String OFFICIAL_QUESTION_TO_ANSWER_ICONS = RedisKeyPrefix.MI_LIAO_API_KEY+"OfficalQuestionToAnswerIcons:";

//    public static final String OFFICIAL_QUESTION_TO_ANSWER_NEW = RedisKeyPrefix.MI_LIAO_API_KEY+"OfficalQuestionToAnswerNew:";

    /**
     * 格式 OfficalQuestionToAnswerByQuestionIdAndPageInfo:{questionId}:{page}:{pageSize}
     */
//    public static final String OFFICIAL_QUESTION_TO_ANSWER_BY_QUESTIONID_AND_PAGEINFO = RedisKeyPrefix.MI_LIAO_API_KEY+
//            "OfficalQuestionToAnswerByQuestionIdAndPageInfo:";

    /**
     * 官方回答的偷听缓存
     * OfficalQuestionToAnswerByEavesdroppingNumber:{官方问题id}:{回答问题Id}
     */
//    public static final String  OFFICIAL_QUESTION_TO_ANSWER_BY_EAVESDROPPING_NUMBER= RedisKeyPrefix.MI_LIAO_API_KEY
//            +"OfficalQuestionToAnswerByEavesdroppingNumber:";


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OfficialQuestionToAnswerDao officialQuestionToAnswerDao;

    @Autowired
    private UserInfoDao userInfoDao;


    /**
     * 获取回答条数
     * @param officialQuestionId
     * @return
     */
//    public Long getNumbers(Integer officialQuestionId){
//
//        String key = OFFICIAL_QUESTION_TO_ANSWER_NUMBERS+officialQuestionId;
//
//        String temp = stringRedisTemplate.opsForValue().get(key);
//
//        if(!StringUtils.isEmpty(temp)){
//
//            return Long.parseLong(temp);
//        }else{
//            return 0L;
//        }
//    }

    /**
     * 更新icons
     * @param officialQuestionId
     */
    public void updateOfficialQuestionToAnswerByIconCache(Integer officialQuestionId){

        List<String> iconList = getIcons(officialQuestionId);

        setOfficialQuestionToAnswerByIcon(iconList, officialQuestionId);

    }

    /**
     * 获取信息Icon信息
     * @param officialQuestionId
     * @return
     */
    public JSONArray getOfficialQuestionToAnswerByIconCache(Integer officialQuestionId){

        String temp = getOfficialQuestionToAnswerByIcon(officialQuestionId);

        if(!StringUtils.isEmpty(temp)){

            return JSONObject.parseArray(temp);
        }else{

            List<String> iconsList = getIcons(officialQuestionId);

            setOfficialQuestionToAnswerByIcon(iconsList,officialQuestionId);

            return JSONObject.parseArray(JSONObject.toJSONString(iconsList));
        }

    }

    /**
     * 获取官方最新回答内容
     * @param officialQuestionId
     * @return
     */
    public OfficialQuestionToAnswerInfo getNewOfficialQuestionToAnswerInfo(Integer officialQuestionId){

        String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_NEW+officialQuestionId;

        String temp = stringRedisTemplate.opsForValue().get(key);

        if(!StringUtils.isEmpty(temp)){
            OfficialQuestionToAnswerInfo obj = JSONObject.parseObject(temp,OfficialQuestionToAnswerInfo.class);
            return obj;
        }else{
            OfficialQuestionToAnswerInfo obj = officialQuestionToAnswerDao
                    .getNewOfficialQuestionToAnswerInfoByOfficialQuestionId(officialQuestionId);

            if(obj !=null){
                stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(obj));
            }

            return obj;
        }

    }

    public void setNewOfficialQuestionToAnswerInfo(OfficialQuestionToAnswerInfo obj){

        String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_NEW+obj.getOfficialQuestionId();

        stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(obj));
    }


    /**
     * 获取icon集合
     * @param officialQuestionId
     * @return
     */
    private List<String> getIcons(Integer officialQuestionId) {
        List<Long> userIds = officialQuestionToAnswerDao.getAnswerIdByOfficialQuestionId(officialQuestionId);

        List<String> iconList = new ArrayList<>(0);

        if(userIds!=null && userIds.size()>0){

            List<User> userList= userInfoDao.getUserListByUserIds(userIds);

            for(User user : userList){
                iconList.add(user.getIcon());
            }

        }
        return iconList;
    }

    private String getOfficialQuestionToAnswerByIcon(Integer officialQuestionId){

        String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_ICONS +officialQuestionId;

        String temp = stringRedisTemplate.opsForValue().get(key);


        return temp;

    }

    private void setOfficialQuestionToAnswerByIcon(List<String> iconList,Integer officialQuestionId){

        if(iconList.size()>0){

            String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_ICONS+officialQuestionId;
            //缓存15分钟
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(iconList),15, TimeUnit.MINUTES);
        }
    }

    public List<OfficialQuestionToAnswerInfo> selectPageInfoByQuestionId(Integer questionId, Integer page,
                                                                         Integer pageSize) {

        String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_BY_QUESTIONID_AND_PAGEINFO
                +questionId+":"+page+":"+pageSize;

        String temp = stringRedisTemplate.opsForValue().get(key);

        if(!StringUtils.isEmpty(temp)){

            List<OfficialQuestionToAnswerInfo> list = new ArrayList<>(0);

            JSONArray jsonArray = JSONObject.parseArray(temp);
            for(int i=0;i<jsonArray.size();i++){
                String str = jsonArray.getString(i);
                OfficialQuestionToAnswerInfo obj = JSONObject.parseObject(str,OfficialQuestionToAnswerInfo.class);
                list.add(obj);
            }
            return list;
        }else{
            Map<String,Object> parameterMap = new HashMap<>(0);

            int startNum = PageUtil.getOffset(page, pageSize);

            parameterMap.put("startNum",startNum);

            parameterMap.put("pageSize",pageSize);

            parameterMap.put("questionId",questionId);

            List<OfficialQuestionToAnswerInfo> list = officialQuestionToAnswerDao.selectPageByQuestionId(parameterMap);

            if(list!=null && list.size()>0){
                stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(list),15,TimeUnit.MINUTES);
            }

            return list;
        }
    }

    /**
     * 更新偷听官方问题回答
     * @param obj
     * @param userId
     */
    public void updateEavesdroppingNumber(OfficialQuestionToAnswerInfo obj, long userId) {
        String userKey=OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_BY_EAVESDROPPING_USER+obj.getOfficialQuestionId()+":"+obj.getId();
        //判断此用户是否偷听过，如果没有自增1
        boolean bl = stringRedisTemplate.opsForSet().isMember(userKey,userId+"");
        if(!bl){
            String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_BY_EAVESDROPPING_NUMBER+obj.getOfficialQuestionId()+":"+obj.getId();
            stringRedisTemplate.opsForValue().increment(key,1);
            //更新
            stringRedisTemplate.opsForSet().add(userKey,userId+"");
        }


    }


    /**
     * 获取偷听次数
     * @param questionId
     * @param answerId
     * @return
     */
    public long getEavesdroppingNumber(int questionId,int answerId){

        String key = OfficialQuestionToAnsweRedisKey.OFFICIAL_QUESTION_TO_ANSWER_BY_EAVESDROPPING_NUMBER+questionId+":"+answerId;
        String number = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(number)){
            return 0;
        }else{
            return Long.parseLong(number);
        }

    }
}
